import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer

function setupDownloadListener(callback) {
  // 先移除旧的监听器
  ipcRenderer.removeAllListeners('download-status')
  // 注册新监听器
  ipcRenderer.on('download-status', (_, data) => {
    callback(data)
    // 监听完成后自动移除（可选，根据需求）
    // ipcRenderer.removeListener('download-status', arguments.callee);
  })
}

const api = {
  fetchData: (data, _object) => ipcRenderer.invoke('fetch-data', data, _object),
  uploadFiles: (data) => ipcRenderer.invoke('upload:files', data),
  onLoadingChange: (callback) => {
    ipcRenderer.on('loading-state', (event, data) => {
      callback(data)
    })
  },
  getLocalIP: () => ipcRenderer.invoke('get-local-ip'),
  // 向主进程发送数据，由主进程调用 electron-store 的 set 方法
  setStoreData: (key, value) => ipcRenderer.invoke('set-store-data', key, value),
  getStoreData: (key) => ipcRenderer.invoke('get-store-data', key),
  getPrinterList: () => ipcRenderer.invoke('get-printer-list'),
  printPage: (pdfUrl, options) => ipcRenderer.invoke('print-page', pdfUrl, options),
  downloadPdf: (pdfUrl, fileName) => ipcRenderer.send('download-pdf', pdfUrl, fileName),
  onDownloadStatus: setupDownloadListener,
  onUserInfoChanged: (callback) =>
    ipcRenderer.on('USER_INFO_CHANGED', (event, data) => callback(data)),
  deleteUser: () => ipcRenderer.invoke('delete-user'),
  changeMain: (data) => ipcRenderer.send('change-main', data)
}
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(222222,error)
  }
} else {
  window.electron = electronAPI
  window.api = api
}
